package com.yang.mybatis.proxy;

import cn.hutool.core.lang.ClassScanner;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapperProxyFactory {
    private Map<Class, MapperProxy> mapperProxyMap = new HashMap<>();

    public MapperProxyFactory(String packageName) {
        // 扫描包
        ClassScanner scanner = new ClassScanner(packageName);
        Set<Class<?>> mapperTypes = scanner.scan();
        for (Class<?> mapperType : mapperTypes) {
            if (!mapperType.isInterface()) {
                // 只对接口进行处理
                continue;
            }

            Map<String, String> mockSqlSession = mockSqlSession(mapperType);
            MapperProxy mapperProxy = new MapperProxy(mockSqlSession, mapperType);
            mapperProxyMap.put(mapperType, mapperProxy);
        }
    }

    public Object newInstance(Class mapperType) {
        MapperProxy mapperProxy = mapperProxyMap.get(mapperType);
        return Proxy.newProxyInstance(mapperType.getClassLoader(),
                new Class[]{mapperType},
                mapperProxy);
    }

    private Map<String, String> mockSqlSession(Class mapperType) {
        Map<String, String> sqlSession = new HashMap<>();
        for (Method method : mapperType.getMethods()) {
            String methodName = method.getName();
            String key = mapperType.getName() + "." + methodName;
            sqlSession.put(key, key);
        }
        return sqlSession;
    }
}